package com.zhifei.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhifei.common.core.redis.RedisCache;
import com.zhifei.common.enums.EmployeeGrowType;
import com.zhifei.common.utils.DispatcherUtils;
import com.zhifei.common.utils.Result;
import com.zhifei.common.utils.StringUtils;
import com.zhifei.system.domain.*;
import com.zhifei.system.service.*;
import com.zhifei.system.util.fxxk.CorpAccessTokenResult;
import com.zhifei.system.util.fxxk.HttpTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class FxxkServiceImpl implements FxxkService {

    public static final String APP_ID = "FSAID_131aa93";
    public static final String APP_SECRET = "589663ba5c7d4c9a9016caa6f71f2ec3";
    public static final String PERMANENT_CODE = "8AE38A235B71ED68E02EB5207AC196BA";
    public static final String CURRENT_OPEN_USERID = "FSUID_6C1D2021028FA79836C06BAFC9E1BF2C";

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DingUserService dingUserService;
    @Autowired
    private EmployeeGrowRecordService employeeGrowRecordService;
    @Autowired
    private PersonProjectService personProjectService;
    @Autowired
    private DevProjectService devProjectService;

    @Override
    public Result listOrderProduct() {
        List<DingUserEntity> dingUserEntityList = dingUserService.lambdaQuery().list();
        JSONObject filterObject = new JSONObject();
        filterObject.put("field_name","field_Q4Rpu__c");
        filterObject.put("field_values", Arrays.asList("1n22qdFhv"));
        filterObject.put("operator","EQ");
        JSONArray orderProductList = new JSONArray();
        JSONObject orderProductResult = this.listCrmOrderProduct(filterObject,"SalesOrderProductObj",0);
        JSONObject orderProductData = orderProductResult.getJSONObject("data");
        Integer total = orderProductData.getInteger("total");
        int totalNum = (int)Math.ceil(total * 1.0 /100);
        JSONArray orderProductListFirst = orderProductData.getJSONArray("dataList");
        orderProductList.addAll(orderProductListFirst);
        if(totalNum>1){
            for(int i=1;i<totalNum;i++){
                JSONObject orderProductResultBrother = this.listCrmOrderProduct(filterObject,"SalesOrderProductObj",i*100);
                JSONObject orderProductDataBrother = orderProductResultBrother.getJSONObject("data");
                JSONArray orderProductListBrother = orderProductDataBrother.getJSONArray("dataList");
                orderProductList.addAll(orderProductListBrother);
            }
        }
        for(int i=0;i<orderProductList.size();i++) {
            JSONObject orderProduct = orderProductList.getJSONObject(i);
            System.out.println("a:"+orderProduct.toString());
            String jobNum = orderProduct.getString("product_code__c");//工号
            String fullName = orderProduct.getString("product_id__r");//姓名
            String userPost = orderProduct.getString("field_eoh01__c__r");//岗位
            String userRank = orderProduct.getString("field_i7t77__c__r");//职级
            String customerName = orderProduct.getString("field_84r2C__c");//所属客户
            String projectName = orderProduct.getString("field_172TR__c");//所属项目
            String orderNo = orderProduct.getString("order_id__r");//所属订单
            String paymentMethod = orderProduct.getString("field_1qRCY__c");//付款方式
            String businessSource = orderProduct.getString("field_2Bxet__c");//商机来源
            System.out.println("#########"+orderNo+"##########"+fullName);
            String admissionDate = orderProduct.getString("field_4E4ah__c");//入场时间
            String estimateLeaveDate = orderProduct.getString("field_3npf1__c");//预计出项时间
            String projectCycle = orderProduct.getString("field_l1l2Y__c");//项目周期（月）
            BigDecimal quoteMonthPay = new BigDecimal(orderProduct.getString("field_Ks8y1__c"));//报价月薪
            BigDecimal monthPay = BigDecimal.ZERO;
            if(StringUtils.isNotEmpty(orderProduct.getString("field_mH1K2__c"))) monthPay = new BigDecimal(orderProduct.getString("field_mH1K2__c"));//薪资
            BigDecimal socialSecurity = BigDecimal.ZERO;
            if(StringUtils.isNotEmpty(orderProduct.getString("field_I11ej__c"))) socialSecurity = new BigDecimal(orderProduct.getString("field_I11ej__c"));//社保公积金
            BigDecimal taxRate = new BigDecimal(orderProduct.getString("field_TnVyb__c"));//税率
            BigDecimal taxAmount = quoteMonthPay.multiply(taxRate.divide(new BigDecimal(100),2, RoundingMode.HALF_UP));//税额（报价月薪*税率）
            BigDecimal grossProfit = quoteMonthPay.subtract(monthPay).subtract(socialSecurity).subtract(taxAmount);//毛利（报价-薪资-社保公积金-税额）
            BigDecimal grossProfitRate = grossProfit.divide(quoteMonthPay,2, RoundingMode.HALF_UP);//毛利率（毛利/报价，如有调整实时更新，低于18%显示红色预警）
            JSONObject owner = orderProduct.getJSONObject("owner__r");
            String serviceManager = owner.getString("name");//业务经理（如果调整需实时更新）
            BigDecimal companyManagementCost = quoteMonthPay.multiply(new BigDecimal(0.1));//公司管理成本（报价*10%）
            BigDecimal riskReserve = quoteMonthPay.multiply(new BigDecimal(0.05));//风险储备金（报价*5%）
            BigDecimal travelExpenses = BigDecimal.ZERO;//差旅费用（初始值为0，后续接口取金蝶中人员差旅成本）
            BigDecimal marketingSubsidies = quoteMonthPay.multiply(new BigDecimal(0.01));//市场营销补贴（报价*1%）
            BigDecimal financialExpenses = quoteMonthPay.multiply(new BigDecimal(0.012));//财务费用（报价*1.2%）
            BigDecimal salesCommission = BigDecimal.ZERO;//销售提成（毛利率<=18%为0，毛利率在18到30%为毛利*2%，毛利率在30%以上为毛利*2.5%）
            BigDecimal commissionRate = BigDecimal.ZERO;//提成比例
            if(grossProfitRate.compareTo(new BigDecimal(0.1))<=0){
                commissionRate = BigDecimal.ZERO;
            }else if(grossProfitRate.compareTo(new BigDecimal(0.1))>0 && grossProfitRate.compareTo(new BigDecimal(0.2))<=0){
                commissionRate = new BigDecimal(0.01);
            }else if(grossProfitRate.compareTo(new BigDecimal(0.2))>0 && grossProfitRate.compareTo(new BigDecimal(0.3))<=0){
                commissionRate = new BigDecimal(0.03);
            }else if(grossProfitRate.compareTo(new BigDecimal(0.3))>0){
                commissionRate = new BigDecimal(0.05);
            }
            //鼓励月结回款，月结项目再加0.5%，独立新拓项目增加1%。
            if(grossProfitRate.compareTo(new BigDecimal(0.1))>0){
                if(StringUtils.isNotEmpty(paymentMethod) && paymentMethod.equals("月结")){
                    commissionRate = commissionRate.add(new BigDecimal(0.005));
                }
                if(StringUtils.isNotEmpty(businessSource) && businessSource.equals("个人开拓")){
                    commissionRate = commissionRate.add(new BigDecimal(0.01));
                }
            }
            salesCommission = grossProfit.multiply(commissionRate);
            BigDecimal recruitCommission = BigDecimal.ZERO;//招聘提成（按照初级250元/人、中级350元/人、高级岗位450元/人；毛利在30%以上增加100元/人）
            if(StringUtils.isNotEmpty(userRank)){
                if(userRank.equals("初级")){
                    recruitCommission = new BigDecimal(250);
                }else if(userRank.equals("初中级") || userRank.equals("中级")){
                    recruitCommission = new BigDecimal(350);
                }else if(userRank.equals("中高级") || userRank.equals("高级")){
                    recruitCommission = new BigDecimal(450);
                }
            }
            if(grossProfitRate.compareTo(new BigDecimal(0.3))>0){
                recruitCommission = recruitCommission.add(new BigDecimal(100));
            }
//            BigDecimal talentServiceCommission = grossProfit.multiply(new BigDecimal(0.02));//人才服务部提成（毛利*2%）
            BigDecimal talentServiceCommission = BigDecimal.ZERO;
            BigDecimal netProfit = grossProfit.subtract(companyManagementCost).subtract(riskReserve).subtract(travelExpenses).
                    subtract(marketingSubsidies).subtract(financialExpenses).subtract(salesCommission).subtract(talentServiceCommission).subtract(recruitCommission);//纯利（毛利-公司管理成本-风险储备金-差旅费用-市场营销补贴-财务费用-销售提成-人才服务部提成）
            BigDecimal netProfitRate = netProfit.divide(quoteMonthPay,2, RoundingMode.HALF_UP);;//纯利率（纯利/报价）
            System.out.println("***************************************************************");
            EmployeeEntity employeeEntity = employeeService.getPreProjectEmployee(jobNum);
            if(employeeEntity!=null){
                employeeEntity.setProjectType(1);
                employeeEntity.setCustomerName(customerName);
                employeeEntity.setProjectName(projectName);
                employeeEntity.setOrderNo(orderNo);
                if(StringUtils.isNotEmpty(admissionDate)){
                    employeeEntity.setAdmissionDate(new Date(DispatcherUtils.parseLong(admissionDate)));
                }
                employeeEntity.setProjectCycle(projectCycle);
                employeeEntity.setQuoteMonthPay(quoteMonthPay);
                employeeEntity.setMonthPay(monthPay);
                employeeEntity.setSocialSecurity(socialSecurity);
                employeeEntity.setTaxRate(taxRate);
                employeeEntity.setTaxAmount(taxAmount);
                employeeEntity.setGrossProfit(grossProfit);
                employeeEntity.setGrossProfitRate(grossProfitRate);
                employeeEntity.setServiceManager(serviceManager);
                if(StringUtils.isNotEmpty(admissionDate)){
                    employeeEntity.setEstimateLeaveDate(new Date(DispatcherUtils.parseLong(estimateLeaveDate)));
                }
                employeeEntity.setCompanyManagementCost(companyManagementCost);
                employeeEntity.setRiskReserve(riskReserve);
                employeeEntity.setTravelExpenses(travelExpenses);
                employeeEntity.setMarketingSubsidies(marketingSubsidies);
                employeeEntity.setFinancialExpenses(financialExpenses);
                employeeEntity.setSalesCommission(salesCommission);
                employeeEntity.setRecruitCommission(recruitCommission);
                employeeEntity.setPaymentMethod(paymentMethod);
                employeeEntity.setBusinessSource(businessSource);
                employeeEntity.setTalentServiceCommission(talentServiceCommission);
                employeeEntity.setNetProfit(netProfit);
                employeeEntity.setNetProfitRate(netProfitRate);
                employeeService.updateById(employeeEntity);
                //更新成长记录表
                for(DingUserEntity dingUserEntity : dingUserEntityList){
                    if(StringUtils.isNotEmpty(jobNum) && jobNum.equals(dingUserEntity.getJobNumber())){
                        if(monthPay.compareTo(dingUserEntity.getMonthPay())!=0){//薪资调整
                            String content = "薪资由"+dingUserEntity.getMonthPay()+"调整为"+monthPay;
                            employeeGrowRecordService.add(EmployeeGrowType.MONTHPAY_CHANGE.getCode(),jobNum,content);
                            dingUserService.lambdaUpdate()
                                    .set(DingUserEntity::getMonthPay,employeeEntity.getMonthPay())
                                    .eq(DingUserEntity::getJobNumber,dingUserEntity.getJobNumber())
                                    .update();
                        }
                        if(quoteMonthPay.compareTo(dingUserEntity.getQuoteMonthPay())!=0){//报价调整
                            String content = "报价由"+dingUserEntity.getQuoteMonthPay()+"调整为"+quoteMonthPay;
                            employeeGrowRecordService.add(EmployeeGrowType.QUOTEMONTHPAY_CHANGE.getCode(),jobNum,content);
                            dingUserService.lambdaUpdate()
                                    .set(DingUserEntity::getQuoteMonthPay,employeeEntity.getQuoteMonthPay())
                                    .eq(DingUserEntity::getJobNumber,dingUserEntity.getJobNumber())
                                    .update();
                        }
                        if(!projectName.equals(dingUserEntity.getProjectName())){//项目调整
                            String content = "项目由"+dingUserEntity.getProjectName()+"调整为"+projectName;
                            employeeGrowRecordService.add(EmployeeGrowType.PROJECTNAME_CHANGE.getCode(),jobNum,content);
                            dingUserService.lambdaUpdate()
                                    .set(DingUserEntity::getProjectName,employeeEntity.getProjectName())
                                    .eq(DingUserEntity::getJobNumber,dingUserEntity.getJobNumber())
                                    .update();
                        }
                        if(socialSecurity.compareTo(dingUserEntity.getSocialSecurity())!=0){//社保公积金调整
                            String content = "社保公积金由"+dingUserEntity.getSocialSecurity()+"调整为"+socialSecurity;
                            employeeGrowRecordService.add(EmployeeGrowType.SOCIALSECURITY_CHANGE.getCode(),jobNum,content);
                            dingUserService.lambdaUpdate()
                                    .set(DingUserEntity::getSocialSecurity,employeeEntity.getSocialSecurity())
                                    .eq(DingUserEntity::getJobNumber,dingUserEntity.getJobNumber())
                                    .update();
                        }
                    }
                }
            }

//            FxxkEmployeeEntity fxxkEmployeeEntity = new FxxkEmployeeEntity();
//            fxxkEmployeeEntity.setJobNum(jobNum);
//            fxxkEmployeeEntity.setFullName(fullName);
//            fxxkEmployeeEntity.setUserPost(userPost);
//            fxxkEmployeeEntity.setUserRank(userRank);
//            fxxkEmployeeEntity.setCustomerName(customerName);
//            fxxkEmployeeEntity.setProjectName(projectName);
//            fxxkEmployeeEntity.setOrderNo(orderNo);
//            fxxkEmployeeEntity.setProjectCycle(projectCycle);
//            fxxkEmployeeEntity.setQuoteMonthPay(quoteMonthPay);
//            fxxkEmployeeEntity.setMonthPay(monthPay);
//            fxxkEmployeeEntity.setSocialSecurity(socialSecurity);
//            fxxkEmployeeEntity.setTaxRate(taxRate);
//            fxxkEmployeeEntity.setTaxAmount(taxAmount);
//            fxxkEmployeeEntity.setGrossProfit(grossProfit);
//            fxxkEmployeeEntity.setGrossProfitRate(grossProfitRate);
//            fxxkEmployeeEntity.setServiceManager(serviceManager);
//            fxxkEmployeeEntity.setCompanyManagementCost(companyManagementCost);
//            fxxkEmployeeEntity.setRiskReserve(riskReserve);
//            fxxkEmployeeEntity.setTravelExpenses(travelExpenses);
//            fxxkEmployeeEntity.setMarketingSubsidies(marketingSubsidies);
//            fxxkEmployeeEntity.setFinancialExpenses(financialExpenses);
//            fxxkEmployeeEntity.setSalesCommission(salesCommission);
//            fxxkEmployeeEntity.setTalentServiceCommission(talentServiceCommission);
//            fxxkEmployeeEntity.setNetProfit(netProfit);
//            fxxkEmployeeEntity.setNetProfitRate(netProfitRate);
//            fxxkEmployeeMapper.insert(fxxkEmployeeEntity);
        }
        return Result.success(orderProductList);
    }

    @Override
    public Result listOrder() {
        JSONObject filterObject = new JSONObject();//项目类型详情为项目制
        filterObject.put("field_name","field_2by26__c");
        filterObject.put("field_values", Arrays.asList("1c5eZUleb"));
        filterObject.put("operator","EQ");
        filterObject.put("field_name","name");
        filterObject.put("field_values", Arrays.asList("DD-ZFJT-RL-20221154","DD-ZFJT-RL-20221165","HT-ZFJT-IT-2022033","DD-ZFJT-RL-2023003"));
        filterObject.put("operator","IN");
        JSONObject orderResult = this.listCrmOrder(filterObject,"SalesOrderObj",0);
        JSONObject orderData = orderResult.getJSONObject("data");
        JSONArray orderList = orderData.getJSONArray("dataList");
        List<PersonProjectEntity> personProjectEntityList = new ArrayList<>();
        for(int i=0;i<orderList.size();i++) {
            JSONObject order = orderList.getJSONObject(i);
            System.out.println("a:" + order.toString());
            PersonProjectEntity personProjectEntity = new PersonProjectEntity();
            String customerName = order.getString("account_id__r");//所属客户
            String projectName = order.getString("field_ck9Sa__c__r");//所属项目
            String orderNo = order.getString("name");//所属订单
            Integer count = personProjectService.lambdaQuery().eq(PersonProjectEntity::getOrderNo,orderNo).count();
            if(count>0){
                continue;
            }
            BigDecimal contractAmount = DispatcherUtils.parseBigDecimal(order.getString("order_amount"));//合同金额
            BigDecimal productCost = DispatcherUtils.parseBigDecimal(order.getString("field_klM10__c"));//人工/商品成本
            BigDecimal purchaseCost = DispatcherUtils.parseBigDecimal(order.getString("field_X2l4x__c"));//采购成本
            BigDecimal taxRate = DispatcherUtils.parseBigDecimal(order.getString("field_4k0ac__c"));//税率
            BigDecimal taxAmount = DispatcherUtils.parseBigDecimal(order.getString("field_284a9__c"));//税额（合同金额*税率）
            BigDecimal grossProfit = DispatcherUtils.parseBigDecimal(order.getString("field_C56JT__c"));//毛利（合同金额-人工/商品成本-采购成本-税额）
            BigDecimal grossProfitRate = DispatcherUtils.parseBigDecimal(order.getString("field_e61h1__c"));//毛利率（毛利/合同金额）
            BigDecimal companyManagementCost = DispatcherUtils.parseBigDecimal(order.getString("field_BzQ1i__c"));//公司管理成本（合同金额*10%）
            BigDecimal riskReserve = DispatcherUtils.parseBigDecimal(order.getString("field_4d9tx__c"));//风险储备金（合同金额*5%）
            BigDecimal travelExpenses = DispatcherUtils.parseBigDecimal(order.getString("field_7szMa__c"));//差旅费用
            BigDecimal marketingSubsidies = DispatcherUtils.parseBigDecimal(order.getString("field_83x62__c"));//市场营销补贴（合同金额*1%）
            BigDecimal financialExpenses = DispatcherUtils.parseBigDecimal(order.getString("field_Y2h40__c"));//财务费用（合同金额*1.2%）
            BigDecimal salesCommission = DispatcherUtils.parseBigDecimal(order.getString("field_Z19yf__c"));//销售提成（毛利*1%）
            BigDecimal otherCost = DispatcherUtils.parseBigDecimal(order.getString("field_2Ctk5__c"));//其他费用
            BigDecimal netProfit = DispatcherUtils.parseBigDecimal(order.getString("field_jCA2r__c"));//纯利（毛利-公司管理成本-风险储备金-差旅费用-市场营销补贴-财务费用-销售提成-招聘提成）
            BigDecimal netProfitRate = DispatcherUtils.parseBigDecimal(order.getString("field_Put2j__c"));//纯利率（纯利/报价）
            String orderTime = order.getString("order_time");//下单时间
            personProjectEntity.setCustomerName(customerName);
            personProjectEntity.setProjectName(projectName);
            personProjectEntity.setOrderNo(orderNo);
            personProjectEntity.setContractAmount(contractAmount);
            personProjectEntity.setProductCost(productCost);
            personProjectEntity.setPurchaseCost(purchaseCost);
            personProjectEntity.setTaxRate(taxRate);
            personProjectEntity.setTaxAmount(taxAmount);
            personProjectEntity.setGrossProfit(grossProfit);
            personProjectEntity.setGrossProfitRate(grossProfitRate);
            personProjectEntity.setCompanyManagementCost(companyManagementCost);
            personProjectEntity.setRiskReserve(riskReserve);
            personProjectEntity.setTravelExpenses(travelExpenses);
            personProjectEntity.setMarketingSubsidies(marketingSubsidies);
            personProjectEntity.setFinancialExpenses(financialExpenses);
            personProjectEntity.setSalesCommission(salesCommission);
            personProjectEntity.setOtherCost(otherCost);
            personProjectEntity.setNetProfit(netProfit);
            personProjectEntity.setNetProfitRate(netProfitRate);
            if(StringUtils.isNotEmpty(orderTime)){
                personProjectEntity.setOrderTime(new Date(DispatcherUtils.parseLong(orderTime)));
            }
            personProjectEntityList.add(personProjectEntity);
        }
        if(personProjectEntityList!=null && personProjectEntityList.size()>0){
            personProjectService.saveBatch(personProjectEntityList);
        }
        return Result.success(orderList);
    }

    @Override
    public Result listDevOrder() {
        JSONObject filterObject = new JSONObject();//项目类型详情为定制开发与集成
        filterObject.put("field_name","field_2by26__c");
        filterObject.put("field_values", Arrays.asList("bV3rgWC78"));
        filterObject.put("operator","EQ");
//        filterObject.put("field_name","name");
//        filterObject.put("field_values", Arrays.asList("DD-ZFJT-IT-20221098","XSDD000113","ZFHT001_21010","DD-ZFJT-IT-2023004"
//            ,"ZFHT001_21024","XSDD000126","DD-ZFJT-CP-20221134","XSDD000108"
//            ,"DD-ZFJT-IT-20221149","DD-ZFJT-IT-20221153","DD-ZFJT-IT-20221169","DD-ZFJT-IT-2023009"));
//        filterObject.put("operator","IN");
        JSONObject orderResult = this.listCrmOrder(filterObject,"SalesOrderObj",0);
        JSONObject orderData = orderResult.getJSONObject("data");
        JSONArray orderList = orderData.getJSONArray("dataList");
        List<DevProjectEntity> devProjectEntityList = new ArrayList<>();
        for(int i=0;i<orderList.size();i++) {
            JSONObject order = orderList.getJSONObject(i);
            System.out.println("a:" + order.toString());
            DevProjectEntity devProjectEntity = new DevProjectEntity();
            String customerName = order.getString("account_id__r");//所属客户
            String projectCode = order.getString("field_B281L__c");//所属项目编码
            String projectName = order.getString("field_ck9Sa__c__r");//所属项目
            String orderNo = order.getString("name");//所属订单
            Integer count = devProjectService.lambdaQuery().eq(DevProjectEntity::getOrderNo,orderNo).count();
            if(count>0){
                continue;
            }
            BigDecimal contractAmount = DispatcherUtils.parseBigDecimal(order.getString("order_amount"));//合同金额
            BigDecimal purchaseCost = DispatcherUtils.parseBigDecimal(order.getString("field_X2l4x__c"));//采购成本
            BigDecimal taxRate = DispatcherUtils.parseBigDecimal(order.getString("field_4k0ac__c"));//税率
            BigDecimal taxAmount = DispatcherUtils.parseBigDecimal(order.getString("field_284a9__c"));//税额（合同金额*税率）
            BigDecimal grossProfit = DispatcherUtils.parseBigDecimal(order.getString("field_C56JT__c"));//毛利（合同金额-人工/商品成本-采购成本-税额）
            BigDecimal grossProfitRate = DispatcherUtils.parseBigDecimal(order.getString("field_e61h1__c"));//毛利率（毛利/合同金额）
            BigDecimal companyManagementCost = DispatcherUtils.parseBigDecimal(order.getString("field_BzQ1i__c"));//公司管理成本（合同金额*10%）
            BigDecimal riskReserve = DispatcherUtils.parseBigDecimal(order.getString("field_4d9tx__c"));//风险储备金（合同金额*5%）
            BigDecimal travelExpenses = DispatcherUtils.parseBigDecimal(order.getString("field_7szMa__c"));//差旅费用
            BigDecimal marketingSubsidies = DispatcherUtils.parseBigDecimal(order.getString("field_83x62__c"));//市场营销补贴（合同金额*1%）
            BigDecimal financialExpenses = DispatcherUtils.parseBigDecimal(order.getString("field_Y2h40__c"));//财务费用（合同金额*1.2%）
            BigDecimal salesCommission = DispatcherUtils.parseBigDecimal(order.getString("field_Z19yf__c"));//销售提成（毛利*1%）
            BigDecimal projectBonus = DispatcherUtils.parseBigDecimal(order.getString("field_J87Ko__c"));//项目奖金包
            BigDecimal softDeptCommission = DispatcherUtils.parseBigDecimal(order.getString("field_2PS2l__c"));//软件事业部提成
            BigDecimal otherCost = DispatcherUtils.parseBigDecimal(order.getString("field_2Ctk5__c"));//其他费用
            BigDecimal netProfit = DispatcherUtils.parseBigDecimal(order.getString("field_jCA2r__c"));//纯利（毛利-公司管理成本-风险储备金-差旅费用-市场营销补贴-财务费用-销售提成-招聘提成）
            BigDecimal netProfitRate = DispatcherUtils.parseBigDecimal(order.getString("field_Put2j__c"));//纯利率（纯利/报价）
            String orderTime = order.getString("order_time");//下单时间
            devProjectEntity.setCustomerName(customerName);
            devProjectEntity.setOrderNo(orderNo);
            devProjectEntity.setProjectCode(projectCode);
            devProjectEntity.setProjectName(projectName);
            devProjectEntity.setContractAmount(contractAmount);
            if(StringUtils.isNotEmpty(orderTime)){
                devProjectEntity.setOrderTime(new Date(DispatcherUtils.parseLong(orderTime)));
            }
            devProjectEntity.setPurchaseCost(purchaseCost);
            devProjectEntity.setTaxRate(taxRate);
            devProjectEntity.setTaxAmount(taxAmount);
            devProjectEntity.setGrossProfit(grossProfit);
            devProjectEntity.setGrossProfitRate(grossProfitRate);
            devProjectEntity.setCompanyManagementCost(companyManagementCost);
            devProjectEntity.setRiskReserve(riskReserve);
            devProjectEntity.setTravelExpenses(travelExpenses);
            devProjectEntity.setMarketingSubsidies(marketingSubsidies);
            devProjectEntity.setProjectBonus(projectBonus);
            devProjectEntity.setFinancialExpenses(financialExpenses);
            devProjectEntity.setSalesCommission(salesCommission);
            devProjectEntity.setSoftDeptCommission(softDeptCommission);
            devProjectEntity.setOtherCost(otherCost);
            devProjectEntity.setNetProfit(netProfit);
            devProjectEntity.setNetProfitRate(netProfitRate);
            devProjectEntityList.add(devProjectEntity);
        }
        if(devProjectEntityList!=null && devProjectEntityList.size()>0){
            devProjectService.saveBatch(devProjectEntityList);
        }
        return Result.success(orderList);
    }

    public CorpAccessTokenResult getToken(){
        // 获取redis中token
        CorpAccessTokenResult corpAccessTokenResult = redisCache.getCacheObject("fxxk_access_token");
        // 判断token是否有值
        if (corpAccessTokenResult==null) {
            // 封装json传参
            JSONObject json = new JSONObject();
            json.put("appId", APP_ID);
            json.put("appSecret", APP_SECRET);
            json.put("permanentCode", PERMANENT_CODE);
            String result = HttpTools.sendPost("https://open.fxiaoke.com/cgi/corpAccessToken/get/V2", json);
            corpAccessTokenResult = JSON.parseObject(result, CorpAccessTokenResult.class);
            if (!Objects.isNull(corpAccessTokenResult) && "0".equals(corpAccessTokenResult.getErrorCode())) {
                redisCache.setCacheObject("fxxk_access_token", corpAccessTokenResult, 7200, TimeUnit.SECONDS);
            }
        }
        corpAccessTokenResult.setCurrentOpenUserId(CURRENT_OPEN_USERID);
        return corpAccessTokenResult;
    }

    public JSONObject getCrmImportantObj(){
        CorpAccessTokenResult corpAccessTokenResult = this.getToken();
        JSONObject corpAccessTokenObject = new JSONObject();
        // 接口处必传的三个数据
        corpAccessTokenObject.put("corpAccessToken", corpAccessTokenResult.getCorpAccessToken());
        corpAccessTokenObject.put("corpId", corpAccessTokenResult.getCorpId());
        corpAccessTokenObject.put("currentOpenUserId", corpAccessTokenResult.getCurrentOpenUserId());
        return corpAccessTokenObject;
    }

    public JSONObject listCrmOrderProduct(JSONObject filterObject,String dataObjectApiName,Integer offset){
        JSONObject paramObject = this.getCrmImportantObj();
        JSONObject dataObject = new JSONObject();
        dataObject.put("dataObjectApiName",dataObjectApiName);
        JSONObject searchQueryInfoObject = new JSONObject();
        JSONObject orderObject = new JSONObject();
        orderObject.put("fieldName","create_time");
        orderObject.put("isAsc",false);
        List<JSONObject> filterObjectList = new ArrayList<>();
        filterObjectList.add(filterObject);
        JSONObject timeFilter = new JSONObject();
        timeFilter.put("field_name","create_time");
        timeFilter.put("field_values", Arrays.asList("11"));
        timeFilter.put("operator","BETWEEN");
        timeFilter.put("value_type","3");
        filterObjectList.add(timeFilter);
        JSONObject statusFilter = new JSONObject();
        statusFilter.put("field_name","field_z2dpe__c");
        statusFilter.put("field_values", Arrays.asList("normal"));
        statusFilter.put("operator","EQ");
        filterObjectList.add(statusFilter);
        searchQueryInfoObject.put("filters",filterObjectList);
        searchQueryInfoObject.put("orders",Arrays.asList(orderObject));
        searchQueryInfoObject.put("limit",100);
        searchQueryInfoObject.put("offset",offset);
        dataObject.put("search_query_info",searchQueryInfoObject);
        paramObject.put("data",dataObject);

        String result = HttpTools.sendPost("https://open.fxiaoke.com/cgi/crm/v2/data/query", paramObject);
        return JSON.parseObject(String.valueOf(result));
    }

    public JSONObject listCrmOrder(JSONObject filterObject,String dataObjectApiName,Integer offset){
        JSONObject paramObject = this.getCrmImportantObj();
        JSONObject dataObject = new JSONObject();
        dataObject.put("dataObjectApiName",dataObjectApiName);
        JSONObject searchQueryInfoObject = new JSONObject();
        JSONObject orderObject = new JSONObject();
        orderObject.put("fieldName","create_time");
        orderObject.put("isAsc",false);
        List<JSONObject> filterObjectList = new ArrayList<>();
        filterObjectList.add(filterObject);
        JSONObject timeFilter = new JSONObject();//创建时间为当天
        timeFilter.put("field_name","create_time");
        timeFilter.put("field_values", Arrays.asList("11"));
        timeFilter.put("operator","BETWEEN");
        timeFilter.put("value_type","3");
        filterObjectList.add(timeFilter);
        JSONObject statusFilter = new JSONObject();//生命状态为正常
        statusFilter.put("field_name","life_status");
        statusFilter.put("field_values", Arrays.asList("normal"));
        statusFilter.put("operator","EQ");
        filterObjectList.add(statusFilter);
        searchQueryInfoObject.put("filters",filterObjectList);
        searchQueryInfoObject.put("orders",Arrays.asList(orderObject));
        searchQueryInfoObject.put("limit",100);
        searchQueryInfoObject.put("offset",offset);
        dataObject.put("search_query_info",searchQueryInfoObject);
        paramObject.put("data",dataObject);

        String result = HttpTools.sendPost("https://open.fxiaoke.com/cgi/crm/v2/data/query", paramObject);
        return JSON.parseObject(String.valueOf(result));
    }


}
